<template>
  <div>
    <!-- 设备登记按钮 -->
    <el-button type="primary" @click="showRegisterDrawer = true">设备登记</el-button>

    <!-- 设备查询条件 -->
    <el-form @submit.prevent="query" :model="queryDevice" label-width="120px" inline>
      <el-form-item label="设备 ID:" prop="deviceId">
        <el-input v-model="queryDevice.deviceId" />
      </el-form-item>
      <el-form-item label="设备状态:" prop="status">
        <el-select v-model="queryDevice.status" placeholder="请选择状态">
          <el-option label="库存中" value="in_stock" />
          <el-option label="使用中" value="in_use" />
          <el-option label="维修中" value="under_maintenance" />
          <el-option label="已报废" value="disposed" />
        </el-select>
      </el-form-item>
      <el-form-item label="设备名称:" prop="deviceName">
        <el-input v-model="queryDevice.deviceName" />
      </el-form-item>
      <el-form-item label="设备型号:" prop="model">
        <el-input v-model="queryDevice.model" />
      </el-form-item>
      <el-form-item label="设备分类:" prop="category">
        <el-input v-model="queryDevice.category" />
      </el-form-item>
      <el-form-item label="设备品牌:" prop="brand">
        <el-input v-model="queryDevice.brand" />
      </el-form-item>
      <el-form-item label="序列号:" prop="serialNumber">
        <el-input v-model="queryDevice.serialNumber" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" native-type="submit">查询</el-button>
      </el-form-item>
    </el-form>

    <!-- 设备登记抽屉 -->
    <el-drawer v-model="showRegisterDrawer" title="设备登记" size="50%">
      <el-form @submit.prevent="register" :model="newDevice" label-width="120px">
        <h2>设备登记</h2>
        <el-form-item label="设备 ID:" prop="deviceId">
          <el-input v-model="newDevice.deviceId" required />
        </el-form-item>
        <el-form-item label="设备名称:" prop="deviceName">
          <el-input v-model="newDevice.deviceName" required />
        </el-form-item>
        <el-form-item label="设备型号:" prop="model">
          <el-input v-model="newDevice.model" />
        </el-form-item>
        <el-form-item label="设备分类:" prop="category">
          <el-input v-model="newDevice.category" />
        </el-form-item>
        <el-form-item label="设备品牌:" prop="brand">
          <el-input v-model="newDevice.brand" />
        </el-form-item>
        <el-form-item label="序列号:" prop="serialNumber">
          <el-input v-model="newDevice.serialNumber" />
        </el-form-item>
        <el-form-item label="购买日期:" prop="purchaseDate">
          <el-date-picker v-model="newDevice.purchaseDate" type="date" />
        </el-form-item>
        <el-form-item label="购买金额:" prop="purchaseAmount">
          <el-input-number v-model="newDevice.purchaseAmount" />
        </el-form-item>
        <el-form-item label="供应商:" prop="supplier">
          <el-input v-model="newDevice.supplier" />
        </el-form-item>
        <el-form-item label="保修期（月）:" prop="warrantyPeriod">
          <el-input-number v-model="newDevice.warrantyPeriod" />
        </el-form-item>
        <el-form-item label="设备状态:" prop="status">
          <el-select v-model="newDevice.status" placeholder="请选择状态">
            <el-option label="库存中" value="in_stock" />
            <el-option label="使用中" value="in_use" />
            <el-option label="维修中" value="under_maintenance" />
            <el-option label="已报废" value="disposed" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门:" prop="departmentId">
          <el-input v-model="newDevice.departmentId" />
        </el-form-item>
        <el-form-item label="设备存放位置:" prop="location">
          <el-input v-model="newDevice.location" />
        </el-form-item>
        <el-form-item label="设备图片链接:" prop="imageUrl">
          <el-input v-model="newDevice.imageUrl" />
        </el-form-item>
        <el-form-item label="备注信息:" prop="remarks">
          <el-input v-model="newDevice.remarks" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">登记</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>

    <!-- 设备列表 -->
    <el-table v-if="devices.length > 0" :data="devices" style="width: 100%">
      <el-table-column prop="deviceId" label="设备 ID" />
      <el-table-column prop="deviceName" label="设备名称" />
      <el-table-column prop="model" label="设备型号" />
      <el-table-column prop="category" label="设备分类" />
      <el-table-column prop="brand" label="设备品牌" />
      <el-table-column prop="serialNumber" label="序列号" />
      <el-table-column prop="purchaseDate" label="购买日期" />
      <el-table-column prop="purchaseAmount" label="购买金额" />
      <el-table-column prop="supplier" label="供应商" />
      <el-table-column prop="warrantyPeriod" label="保修期（月）" />
      <el-table-column
          prop="status"
          label="设备状态"
          :formatter="formatStatus"
      />
      <el-table-column prop="departmentName" label="所属部门" />
      <el-table-column prop="location" label="设备存放位置" />
      <el-table-column prop="imageUrl" label="设备图片链接" />
      <el-table-column prop="remarks" label="备注信息" />
      <!-- 新增列：分配类型 -->
      <el-table-column label="分配类型" width="100">
        <template #default="scope">
          {{ scope.row.useType }}
        </template>
      </el-table-column>
      <!-- 新增列：部门名称或使用人 -->
      <el-table-column label="部门名称/使用人" width="180">
        <template #default="scope">
          <div v-if="scope.row.useType === '部门申请'">
            {{ scope.row.useDepartmentName }}
          </div>
          <div v-else>
            {{ scope.row.userName }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template #default="scope">
          <el-button @click="editDevice(scope.row)">编辑</el-button>
          <el-button @click="deleteDevice(scope.row)" type="danger">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 设备更新抽屉 -->
    <el-drawer v-model="showUpdateDrawer" title="设备更新" size="50%">
      <el-form v-if="editingDevice" @submit.prevent="update" :model="editingDevice" label-width="120px">
        <h2>设备更新</h2>
        <el-form-item label="设备 ID:" prop="deviceId">
          <el-input v-model="editingDevice.deviceId" disabled />
        </el-form-item>
        <el-form-item label="设备名称:" prop="deviceName">
          <el-input v-model="editingDevice.deviceName" />
        </el-form-item>
        <el-form-item label="设备型号:" prop="model">
          <el-input v-model="editingDevice.model" />
        </el-form-item>
        <el-form-item label="设备分类:" prop="category">
          <el-input v-model="editingDevice.category" />
        </el-form-item>
        <el-form-item label="设备品牌:" prop="brand">
          <el-input v-model="editingDevice.brand" />
        </el-form-item>
        <el-form-item label="序列号:" prop="serialNumber">
          <el-input v-model="editingDevice.serialNumber" />
        </el-form-item>
        <el-form-item label="购买日期:" prop="purchaseDate">
          <el-date-picker v-model="editingDevice.purchaseDate" type="date" />
        </el-form-item>
        <el-form-item label="购买金额:" prop="purchaseAmount">
          <el-input-number v-model="editingDevice.purchaseAmount" />
        </el-form-item>
        <el-form-item label="供应商:" prop="supplier">
          <el-input v-model="editingDevice.supplier" />
        </el-form-item>
        <el-form-item label="保修期（月）:" prop="warrantyPeriod">
          <el-input-number v-model="editingDevice.warrantyPeriod" />
        </el-form-item>
        <el-form-item label="设备状态:" prop="status">
          <el-select v-model="editingDevice.status" placeholder="请选择状态">
            <el-option label="库存中" value="in_stock" />
            <el-option label="使用中" value="in_use" />
            <el-option label="维修中" value="under_maintenance" />
            <el-option label="已报废" value="disposed" />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门:" prop="departmentId">
          <el-input v-model="editingDevice.departmentId" />
        </el-form-item>
        <el-form-item label="设备存放位置:" prop="location">
          <el-input v-model="editingDevice.location" />
        </el-form-item>
        <el-form-item label="设备图片链接:" prop="imageUrl">
          <el-input v-model="editingDevice.imageUrl" />
        </el-form-item>
        <el-form-item label="备注信息:" prop="remarks">
          <el-input v-model="editingDevice.remarks" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" native-type="submit">更新</el-button>
          <el-button @click="cancelEdit">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import {
  registerDevice,
  queryDevices,
  updateDevice,
  deleteDevice as deleteDeviceApi
} from '@/api/device.js';

// 控制抽屉显示
const showRegisterDrawer = ref(false);
const showUpdateDrawer = ref(false);

// 新设备信息
const newDevice = ref({
  deviceId: '',
  deviceName: '',
  model: '',
  category: '',
  brand: '',
  serialNumber: '',
  purchaseDate: '',
  purchaseAmount: '',
  supplier: '',
  warrantyPeriod: '',
  status: 'in_stock', // 默认值为库存中
  departmentId: '',
  location: '',
  imageUrl: '',
  remarks: ''
});

// 查询设备信息
const queryDevice = ref({
  deviceId: '',
  status: '',
  deviceName: '',
  model: '',
  category: '',
  brand: '',
  serialNumber: ''
});

// 设备列表
const devices = ref([]);

// 正在编辑的设备信息
const editingDevice = ref(null);

// 页面加载时默认查询一次数据
onMounted(() => {
  query();
});

// 设备登记
const register = async () => {
  try {
    const response = await registerDevice(newDevice.value);
    console.log(response.data);
    // 清空表单
    newDevice.value = {
      deviceId: '',
      deviceName: '',
      model: '',
      category: '',
      brand: '',
      serialNumber: '',
      purchaseDate: '',
      purchaseAmount: '',
      supplier: '',
      warrantyPeriod: '',
      status: 'in_stock', // 默认值为库存中
      departmentId: '',
      location: '',
      imageUrl: '',
      remarks: ''
    };
    // 关闭抽屉
    showRegisterDrawer.value = false;
    // 重新查询设备列表
    await query();
  } catch (error) {
    console.error(error);
  }
};

// 设备查询
const query = async () => {
  try {
    const response = await queryDevices(queryDevice.value);
    // 确保设备列表数据正确赋值
    devices.value = response.data || [];
  } catch (error) {
    console.error(error);
  }
};

// 编辑设备
const editDevice = (device) => {
  editingDevice.value = { ...device };
  showUpdateDrawer.value = true;
};

// 取消编辑
const cancelEdit = () => {
  editingDevice.value = null;
  showUpdateDrawer.value = false;
};

// 设备更新
const update = async () => {
  try {
    const updatedDevice = { ...editingDevice.value };
    const response = await updateDevice(updatedDevice);
    // 更新设备列表中的对应设备信息
    const index = devices.value.findIndex(device => device.deviceId === response.data.deviceId);
    if (index !== -1) {
      devices.value[index] = response.data;
    }
    // 取消编辑
    cancelEdit();
    // 重新查询设备列表以刷新数据
    await query();
  } catch (error) {
    console.error('设备更新失败:', error);
  }
};

// 设备删除
const deleteDevice = async (device) => {
  try {
    const response = await deleteDeviceApi(device);
    console.log(response.data);
    // 重新查询设备列表
    await query();
  } catch (error) {
    console.error(error);
  }
};

// 格式化设备状态
const formatStatus = (row, column, cellValue) => {
  const statusMap = {
    in_stock: '库存中',
    in_use: '使用中',
    under_maintenance: '维修中',
    disposed: '已报废'
  };
  return statusMap[cellValue] || '未知状态';
};
</script>
